﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;

using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
using Amazon.SimpleDB;
using Amazon.SimpleDB.Model;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;

namespace Aws.ConsoleApp1
{
    class Program
    {
        static string bucketName = "ecsbucket";
        static string accessKeyId = "AKIAIYQJPQGTICRALRCQ";
        static string secretAccessKeyId = "5EqsVfpmCd6C6gwkspxW6rPgP5MPp2KC2JnhWi5e";
        static IAmazonS3 client;
        static int maxKey = 10;

        public static void Main(string[] args)
        {


            using (client = new AmazonS3Client(
                accessKeyId, secretAccessKeyId, Amazon.RegionEndpoint.APSoutheast1))
            {


                var key = "app/uploadfiles/179/images/1604585_620396137997367_1865827635_n.jpg";



                var preSignedURLRequest = new Amazon.S3.Model.GetPreSignedUrlRequest
                {
                    BucketName = bucketName,
                    Expires = DateTime.Now.AddMinutes(1),
                    Key = key,
                    Protocol = Protocol.HTTPS
                };
                var response = client.GetPreSignedURL(preSignedURLRequest);

                ListingObjects();


                //Console.WriteLine("Listing objects stored in a bucket");

                

                //var path = @"E:\tmp\image1.png";
                //var stream = System.IO.File.OpenRead(path);

                //var extension = Path.GetExtension(path);

                //var fileInfo = new FileInfo(path);
                //var stream = fileInfo.OpenRead();

                //var request = new GetObjectRequest
                //{
                //    BucketName = bucketName,
                //    Key = "web/image1.png",
                //    //ResponseExpires = DateTime.No
                //};


                //client.DeleteObject(new DeleteObjectRequest {})



                // 1. create request
                //var initiateMultipartRequest = new InitiateMultipartUploadRequest
                //{
                //    BucketName = bucketName,
                //    Key = DateTime.Now.Ticks.ToString() + fileInfo.Extension,
                //};

                //InitiateMultipartUploadResponse initResponse = client.InitiateMultipartUpload(initiateMultipartRequest);

                //// 2. Upload Parts.
                //long contentLength = fileInfo.Length;
                //long partSize = 5242880; // 5 MB

                //try
                //{
                //    long filePosition = 0;
                //    for (int i = 1; filePosition < contentLength; i++)
                //    {

                //        // Create request to upload a part.
                //        UploadPartRequest uploadRequest = new UploadPartRequest
                //        {
                //            BucketName = existingBucketName,
                //            Key = keyName,
                //            UploadId = initResponse.UploadId,
                //            PartNumber = i,
                //            PartSize = partSize,
                //            FilePosition = filePosition,
                //            FilePath = filePath
                //        };

                //        // Upload part and add response to our list.
                //        uploadResponses.Add(s3Client.UploadPart(uploadRequest));

                //        filePosition += partSize;
                //    }

                //    // Step 3: complete.
                //    CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
                //    {
                //        BucketName = existingBucketName,
                //        Key = keyName,
                //        UploadId = initResponse.UploadId,
                //    };

                //    CompleteMultipartUploadResponse completeUploadResponse =
                //        s3Client.CompleteMultipartUpload(compRequest);

                //}
                //catch (Exception exception)
                //{
                //    Console.WriteLine("Exception occurred: {0}", exception.Message);
                //    AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest
                //    {
                //        BucketName = existingBucketName,
                //        Key = keyName,
                //        UploadId = initResponse.UploadId
                //    };
                //    s3Client.AbortMultipartUpload(abortMPURequest);
                //}


                //client.InitiateMultipartUpload()

                //var filePath = "image.jpg";
                //var generateFileName = true;
                //var rootFolderStorage = "app/uploadfiles/";


                //if (filePath.StartsWith("/")) filePath = filePath.TrimStart('/');

                //var fileName = (generateFileName ? (DateTime.UtcNow.Ticks.ToString() + System.IO.Path.GetExtension(filePath)) : System.IO.Path.GetFileName(filePath));

                //var index = filePath.IndexOf(fileName);

                //var keyName = rootFolderStorage + filePath.Substring(0, filePath.LastIndexOf("/") + 1) + fileName;

                //TransferUtility transfer = new TransferUtility(client);


                //var path = @"E:\tmp\image1.png";
                //var stream = System.IO.File.OpenRead(path);

                //var extension = Path.GetExtension(path);

                //var transferRequest = new TransferUtilityUploadRequest
                //{
                //    BucketName = bucketName,
                //    InputStream = stream,
                //    Key = rootFolderStorage + DateTime.Now.Ticks.ToString() + extension,
                //    CannedACL = S3CannedACL.Private
                //};
                //transfer.Upload(transferRequest);
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();



            Console.Read();
        }

        static void ListingObjects()
        {
            try
            {
                ListObjectsRequest request = new ListObjectsRequest
                {
                    BucketName = bucketName,
                    MaxKeys = maxKey
                };

                do
                {
                    ListObjectsResponse response = client.ListObjects(request);
                    //client.

                    // Process response.
                    foreach (S3Object entry in response.S3Objects)
                    {
                        var preSignedUrl = client.GetPreSignedURL(new GetPreSignedUrlRequest
                        {
                            BucketName = bucketName,
                            Key = entry.Key,
                            Expires = DateTime.Now.AddMinutes(2)
                        });

                        Console.WriteLine("key = {0} size = {1} PreSignedURL = {2}",
                            entry.Key, entry.Size, preSignedUrl);
                        Console.WriteLine();



                    }

                    // If response is truncated, set the marker to get the next 
                    // set of keys.

                    if (response.IsTruncated)
                    {
                        request.Marker = response.NextMarker;
                    }
                    else
                    {
                        request = null;
                    }
                } while (request != null);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Check the provided AWS Credentials.");
                    Console.WriteLine(
                    "To sign up for service, go to http://aws.amazon.com/s3");
                }
                else
                {
                    Console.WriteLine(
                     "Error occurred. Message:'{0}' when listing objects",
                     amazonS3Exception.Message);
                }
            }
        }
    }
}